
package com.cw.filter;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import com.alibaba.fastjson.JSON;
import com.cw.common.Constants;
import com.cw.common.R;
import com.cw.config.BaseContext;
import com.cw.entity.Employee;
import com.cw.entity.Runner;
import com.cw.entity.User;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.index.PathBasedRedisIndexDefinition;
import org.springframework.util.AntPathMatcher;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;


@Slf4j
@WebFilter("/*")
public class LoginCheckFilter implements Filter {

/**
     * //路径匹配器
     * //支持通配符
     */


    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    @Resource
    private RedisTemplate redisTemplate;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest request1, ServletResponse response1, FilterChain filterChain) throws IOException, ServletException {
        //1.获取用户uri
        //1.1类型转换获取到更多的方法
        HttpServletResponse response = (HttpServletResponse) response1;
        HttpServletRequest request = (HttpServletRequest) request1;
        String requestURI = request.getRequestURI();
//        2.放行页面，登录相关的接口
        String [] uris = new String[]{
                "/employee/login",
                "/user/sendMsg",
                "/user/login",
                "/category/list",
                "/images/**",
                "/common/upload",
                "/common/download",
        };
        boolean check = check(uris,requestURI);
        if (check) {
            filterChain.doFilter(request,response);
            return;
        }else{
            String access_token = request.getHeader("Authorization");
            String currentId = String.valueOf(JWTUtil.parseToken(access_token).getPayload("current_id"));
            BaseContext.setCurrentId(Long.valueOf(currentId));
            System.out.println("token_id:"+currentId);
            boolean verify = JWTUtil.verify(access_token,Constants.SECRET_KEY.getBytes(StandardCharsets.UTF_8));
            if (verify){
                filterChain.doFilter(request,response);
                return;
            }
        }
        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(JSON.toJSONString(R.error("NOT_LOGIN")));
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
/**
     *路径匹配器，检测本次请求是否需要放行
     * @param uris 白名单
     * @param requestURI 测试路径
     * @return 如果为true 放行 ， false 拦截
     */

    public boolean check(String [] uris, String requestURI) {
        for (String uri : uris) {
            boolean match = PATH_MATCHER.match(uri, requestURI);
            if (match){
                return true;
            }
        }
        return false;
    }
}
